import { PlusOutlined, DownloadOutlined } from '@ant-design/icons';
import {Button, Divider, message, TreeSelect, Popconfirm, Select, Upload, Image, Modal, DatePicker} from 'antd';
import React, { useState, useRef, useEffect, useLayoutEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import { UploadOutlined, FormOutlined } from '@ant-design/icons';
import Access from '@/components/Access/Access';
import Dashboard from '../Dashboard';
import { money_trans, saveFileAs, transTitle } from '@/utils/utils';
import defaultSetting from '@/../config/defaultSettings';
import FormItem from 'antd/lib/form/FormItem';

import {
  queryRule,
  updateRule,
  addRule,
  removeRule,
  getDictionary,
  queryDepartment,
  getCaptcha,
  allStore,
  storeCommodity,
  commodityUpdate,
  exportStoreStock,
  exportStore,
  commodityUpdatePrice,
  lklAddTerm
} from './service';
import styles from '../../../global.less';
import {exportOrderByStores, storeBaseList} from "@/pages/OrderManagement/StoreOrder/service";
import UploadImg from "@/components/UploadImg";
import {del} from "@/pages/SupplyChainManagement/PurchaseManagement/UnifyPurchase/UnifyPurchaseList/service";
const { Option } = Select;
const lklCodeUrl = "https://www.koseful.com/file/lkl/LKL_CODE.xlsx";
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields, actionRef) => {
  const hide = message.loading('正在添加');

  try {
    const { res } = await addRule({ ...fields });
    hide();
    message.success('添加成功');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param payload
 */

const handleUpdate = async (payload, actionRef) => {
  const hide = message.loading('正在修改');

  try {
    const { res } = await updateRule(payload);
    hide();
    res ? message.success('修改成功') : null;
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};
const handleUpdatePrice = async (payload, actionRef) => {
  const hide = message.loading('正在修改');
  try {
    const { res } = await commodityUpdatePrice(payload);
    hide();
    res ? message.success('修改成功') : null;
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (payload, actionRef) => {
  const hide = message.loading('正在删除');

  try {
    await removeRule(payload);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [codeModalVisible, handleCodeModalVisible] = useState(false);
  const [createEditModalVisible, handleEditModalVisible] = useState(false);
  const [uploadLoading, setUploadLoading] = useState(false);
  const [storeDashboardModalVisible, handleStoreDashboardModalVisible] = useState(false);
  const [formValue, setFormValue] = useState(null);
  const [pointData, setPointData] = useState({});
  const [commodityState, handleCommodityState] = useState(false);
  const [commodityForms, handleCommodityForms] = useState();
  const [priceState, handlePriceState] = useState(false);
  const [storeList, handleStoreList] = useState({});
  const [must, setMust] = useState(true);
  const [count, setCount] = useState({});
  const [commodityCount, setCommodityCount] = useState();
  const [treeValue, setTreeValues] = useState([]);
  const [parentValue, setParentValues] = useState([]);
  const [menuValues, setMenuValues] = useState([]);
  const [areaSure, setAreaSure] = useState(true);
  const actionRef = useRef();
  const commodityRef = useRef();
  const formRef = useRef();
  const [province, setProvince] = useState([]);
  const [city, setCity] = useState([]);
  const [area, setArea] = useState([]);
  const [typeArr, setTypeArr] = useState(['化肥', '超市']);
  const [department, setDepartment] = useState([]);
  const [areaState, setAreaState] = useState(true);
  const [cityState, setCityState] = useState(true);
  const [storeId, setStoreId] = useState();
  const [codeUrl, setCodeUrl] = useState('');
  const [storeArray, setStoreArray] = useState([]);
  const [stores, setStores] = useState([]);
  const [outModal, handleOutModal] = useState(false);
  const [storeLicense, setStoreLicense] = useState(null);
  const [addLklTerm, handleAddLklTerm] = useState(false);
  const [lklTerm, setLklTerm] = useState({});
  const [submitButtonLoading, handSubmitButtonLoading] = useState(false);
  const getStore = () => {
    storeBaseList()
      .then((res) => {
        const {code} = res;
        if (code === 0){
          setStoreArray(res.data);
          let list = [];
          res.data.forEach(ts=>{
            list = list.concat(ts.stores);
          });
          setStores(list);
        }else{
          message.info(res.message);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const getCode = (payload) => {
    getCaptcha(payload).then((res) => {
      const codeUrl = window.URL.createObjectURL(res.data);
      setCodeUrl(codeUrl);
    });
  };
  const handleChoicePlace = (e) => {
    if (e.hasOwnProperty('point')) {
      setPointData(e);
    }
  };
  const uploadOnChange = (info) => {
    setUploadLoading(true);
    if (info.file.status === 'done') {
      setUploadLoading(false);
      const {
        file: {
          response: { code },
        },
      } = info;
      if (code == 0) {
        actionRef.current.reload();
        message.success('导入成功');
      } else {
        message.error('导入失败请重试！');
      }
    } else {
      // message.error('导入失败请重试！');
    }
  };

  const handleProvince = async (value, index) => {
    if (
      value === '1372759026386952193' ||
      value === '1372759018577158146' ||
      value === '1372759017524387842'
    ) {
      setMust(false);
    } else {
      setMust(true);
    }
    await getDictionary('city', value).then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setCityState(false);
        setCity(data);
      }
    });
  };

  const handleCity = async (value, index) => {
    await getDictionary('area', value).then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setAreaState(false);
        setArea(data);
        data.length === 0 ? setAreaSure(false) : null;
      }
    });
  };

  const TreeOnChange = (value) => {
    setTreeValues(value);
  };
  const ListOnChange = (value) => {
    setParentValues(value);
  };
  const getProvince = () => {
    getDictionary('province').then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setProvince(data);
      }
    });
    getDictionary('city').then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setCity(data);
      }
    });
    getDictionary('area').then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setArea(data);
      }
    });
  };
  const handleDepartment = async () => {
    try {
      await queryDepartment().then((res) => {
        if (res.code === 0) {
          const { data } = res;
          transTitle(data);
          setDepartment(data);
        }
      });
    } catch (error) {
      return false;
    }
  };
  const handleParentList = async () => {
    try {
      await allStore().then((res) => {
        const { data } = res;
        transTitle(data);
        setMenuValues(data);
      });
    } catch (error) {
      return false;
    }
  };
  const handleSetStoreLicense = (payload) => {
    setStoreLicense(payload.url);
  };
  useEffect(() => {
    getProvince();
    handleDepartment();
    handleParentList();
    getStore();
  }, []);
  const commodityColumns1 = [

    {
      title: '品项名',
      dataIndex: 'goodsItemName',
      valueType: 'text',
      hideInForm: true,
      width: 120,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '条码号',
      dataIndex: 'goodsBarCode',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '成本价',
      dataIndex: 'cost',
      valueType: 'text',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '成本价为必填项',
          },
        ],
      },
    },
    {
      title: '市场价',
      dataIndex: 'price',
      valueType: 'text',
      hideInSearch: true,
      render: (dom) => {
        return money_trans(dom);
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '会员价',
      dataIndex: 'memberPrice',
      valueType: 'text',
      hideInSearch: true,
      render: (dom) => {
        return money_trans(dom);
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '积分价',
      dataIndex: 'integralPrice',
      valueType: 'text',
      hideInSearch: true,

      render: (dom) => {
        return money_trans(dom);
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '公司成本价',
      dataIndex: 'companyCost',
      hideInSearch: true,
    },
    {
      title: '公司库存',
      dataIndex: 'companyStock',
      hideInSearch: true,
    },
    {
      title: '结算周期',
      dataIndex: 'cycleType',
      hideInSearch: true,
      valueEnum: {
        3: {
          text: '周结',
          status: 'Processing',
        },
        4: {
          text: '月结',
          status: 'Success',
        },
      },
    },
    {
      title: '价格类型',
      dataIndex: 'priceType',
      hideInSearch: true,
      valueEnum: {
        1: {
          text: '总部价格',
          status: 'Processing',
        },
        2: {
          text: '店铺价格',
          status: 'Success',
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select defaultValue={defaultRender.priceType} placeholder="请选择价格类型" allowClear>
            <Option value={1}>总部价格</Option>
            <Option value={2}>店铺价格</Option>
          </Select>
        );
      },
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 80,
      render: (_, record) => {
        return (
          <Access accessKey={"@updateStorePrice"}>
            <a
              onClick={() => {
                handleCommodityForms(record);
                handlePriceState(true);
              }}
            >
              修改价格
            </a>
          </Access>

        );
      },
    },
  ];
  const commodityColumns2 = [
    {
      title: '成本价',
      dataIndex: 'cost',
      valueType: 'text',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '成本价为必填项',
          },
        ],
      },
    },
    {
      title: '标价',
      dataIndex: 'price',
      valueType: 'text',
      hideInSearch: true,
      render: (dom) => {
        return money_trans(dom);
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '会员价',
      dataIndex: 'memberPrice',
      valueType: 'text',
      hideInSearch: true,
      render: (dom) => {
        return money_trans(dom);
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '积分价',
      dataIndex: 'integralPrice',
      valueType: 'text',
      hideInSearch: true,

      render: (dom) => {
        return money_trans(dom);
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '注:',
      dataIndex: 'tips',
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return <div>此处修改表示修改为【店铺授权价】</div>;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 80,
      render: (_, record) => {
        return (
          <Access accessKey={"@updateStorePrice"}>
            <a
              onClick={() => {
                handleCommodityForms(record);
                handlePriceState(true);
              }}
            >
              修改价格
            </a>
          </Access>
        );
      },
    },
  ];
  const outColumns = [
    {
      title: '店铺',
      // hideInSearch: true,
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择店铺"
            showSearch
            filterOption={(input, option) => {
              if (option.options){
                option.options.map((data=>{
                  return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }))
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }else {
                return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }
            }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
                return (
                  <Select.OptGroup label={item_.posName}>
                    {
                      item_.stores.map((item_s, index_s) => {
                        return (
                          <Select.Option value={item_s.id} key={item_s.id} >
                            {item_s.name}
                          </Select.Option>
                        );
                      })
                    }
                  </Select.OptGroup>
                );
              })}
          </Select>
        );
      },
    },
  ];
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '联系人',
      dataIndex: 'contacts',
      valueType: 'text',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '联系人为必填项',
          },
        ],
      },
    },
    {
      title: '所属区域',
      dataIndex: 'deptId',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false} className="formItem_div">
            <TreeSelect
              showSearch
              // style={{ width: '400px' }}
              value={treeValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择所属区域"
              allowClear
              treeDataSimpleMode
              treeData={department}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onChange={TreeOnChange}
            />
          </FormItem>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '所属区域为必选项',
          },
        ],
      },
    },
    {
      title: '联系人电话',
      dataIndex: 'tel',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '联系人电话为必填项',
          },
        ],
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueType: 'text',
      render: (_, record) => {
        return <span>{record.type === 1 ? '化肥' : (record.type === 2 ? '超市':'一店一超') }</span>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择类型" allowClear>
            {typeArr.map((item_, index) => {
              return (
                <Option value={index + 1} key={index}>
                  {item_}
                </Option>
              );
            })}
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '类型为必填项',
          },
        ],
      },
    },
    {
      title: '经营类型',
      dataIndex: 'subType',
      valueType: 'text',
      hideInSearch: true,
      hideInTable:true,
      render: (_, record) => {
        return <span>{record.subType === 0 ? '自营' : (record.type === 1 ? '加盟':(record.type === 2 ? '闭店':'其他')) }</span>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择类型" allowClear>
            <Select.Option value={0}>自营</Select.Option>
            <Select.Option value={1}>加盟</Select.Option>
            <Select.Option value={2}>闭店</Select.Option>
            <Select.Option value={3}>其他</Select.Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '经营类型为必填项',
          },
        ],
      },
    },
    {
      title: '业务周期',
      dataIndex: 'cycleType',
      valueType: 'text',
      hideInSearch: true,
      hideInTable:true,
      render: (_, record) => {
        return <span>{record.subType === 0 ? '开发期' : (record.type === 1 ? '成熟期':(record.type === 2 ? '帮扶期':(record.type === 3 ? '商超自营期':'商超经营期'))) }</span>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择业务周期" allowClear>
            <Select.Option value={0}>开发期</Select.Option>
            <Select.Option value={1}>成熟期</Select.Option>
            <Select.Option value={2}>帮扶期</Select.Option>
            <Select.Option value={3}>商超自营期</Select.Option>
            <Select.Option value={4}>商超经营期</Select.Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '业务周期为必填项',
          },
        ],
      },
    },
    {
      title: '店铺级别',
      dataIndex: 'levelType',
      valueType: 'text',
      hideInSearch: true,
      hideInTable:true,
      render: (_, record) => {
        return <span>{record.subType === 1 ? '镇级' : "村级" }</span>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择店铺级别" allowClear>
            <Select.Option value={1}>镇级</Select.Option>
            <Select.Option value={2}>村级</Select.Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '店铺级别为必填项',
          },
        ],
      },
    },
    {
      title: '保证金',
      dataIndex: 'marginMoney',
      valueType: 'text',
      hideInSearch: true,
      hideInTable:true,
    },
    {
      title: '所在省',
      dataIndex: 'provinceId',
      valueType: 'text',
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择所在省" allowClear onSelect={handleProvince}>
            {province.map((item_, index) => {
              return (
                <Option value={item_.id} key={index}>
                  {item_.name}
                </Option>
              );
            })}
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '所在省为必选项',
          },
        ],
      },
    },
    {
      title: '所在市',
      dataIndex: 'cityId',
      valueType: 'text',

      hideInTable: true,
      hideInForm: !must,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择所在市" disabled={cityState} allowClear onSelect={handleCity}>
            {city.map((item_, index) => {
              return (
                <Option value={item_.id} key={index}>
                  {item_.name}
                </Option>
              );
            })}
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: must,
            message: '所在市为必选项',
          },
        ],
      },
    },
    {
      title: '所在区县',
      dataIndex: 'areaId',
      valueType: 'text',

      hideInTable: true,
      hideInForm: !must,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择所在区县" allowClear disabled={areaState}>
            {area.map((item_, index) => {
              return (
                <Option value={item_.id} key={index}>
                  {item_.name}
                </Option>
              );
            })}
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: must && areaSure,
            message: '所在区县为必选项',
          },
        ],
      },
    },
    {
      title: '地址',
      dataIndex: 'address',
      hideInTable: true,
      hideInSearch: true,
      sort: 1,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '地址为必填项',
          },
        ],
      },
    },
    {
      title: '经度',
      dataIndex: 'longitude',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '纬度',
      dataIndex: 'latitude',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '在线销售',
      dataIndex: 'isOnline',
      valueType: 'text',
      render: (_, record) => {
        return <span>{record.isOnline ? '是' : '否' }</span>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="是否在线销售(惠民购)" allowClear>
            <Option value={true} key={true}>
              是
            </Option>
            <Option value={false} key={false}>
              否
            </Option>
          </Select>
        );
      },
    },
    {
      title: '配送费',
      dataIndex: 'freight',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '免配起步价',
      dataIndex: 'freeFreight',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '配送范围(公里)',
      dataIndex: 'delivery',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '邮编',
      dataIndex: 'postcode',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '营业执照',
      dataIndex: 'storeLicense',
      width: 200,
      hideInSearch: true,
      render: (_, payload) => {
        return <>{_ !== '-' ? <Image className={styles.img_div} src={_} /> : null}</>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <>
            {storeLicense ? (
              <FormItem name="storeLicense">
                <UploadImg
                  imgUrl={storeLicense}
                  showImgUrl={storeLicense}
                  subpath="storeLicense"
                  handleSetFacePicture={handleSetStoreLicense}
                />
              </FormItem>
            ) : (
              <FormItem name="storeLicense">
                <UploadImg subpath="storeLicense" handleSetFacePicture={handleSetStoreLicense} />
              </FormItem>
            )}
          </>
        );
      },
    },
    {
      title: '关联店铺',
      dataIndex: 'storeJoin',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        const isOnline = form.getFieldValue("isOnline");
        return isOnline ? (
          <Select
            placeholder="请选择关联店铺"
            showSearch
            allowClear
            filterOption={(input, option) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {stores.map((item_, index) => {
              return (
                <Select.Option value={item_.id} key={item_.id}>
                  {item_.name}
                </Select.Option>
              );
            })}
          </Select>
        ) : null;


      },
    },
    {
      title: '地采频率',
      dataIndex: 'purchaseNumber',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '统采频率',
      dataIndex: 'unifyPurchaseNumber',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '开户行',
      dataIndex: 'bankName',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '银行卡号',
      dataIndex: 'bankNumber',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '合同编号',
      dataIndex: 'contractNumber',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '签约日期',
      dataIndex: 'contractStartDate',
      valueType: 'date',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '身份证号',
      dataIndex: 'idNumber',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '合同到期日期',
      dataIndex: 'contractEndDate',
      valueType: 'date',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 170,
      render: (_, record) => (
        <>
          <Access accessKey={"@updateStoreDetail"}>
            <a
              onClick={async () => {
                setPointData({
                  address: record.address,
                  point: {
                    lat: record.lat,
                    lng: record.lng,
                  },
                });
                setTreeValues({ value: record.parentId, label: record.address });
                handleEditModalVisible(true);
                setFormValue(record);
                // setCityState(false);
                // setAreaState(false);
                setAreaSure(true);
                if (record.storeLicense){
                  setStoreLicense(record.storeLicense);
                }else {
                  setStoreLicense(null);
                }
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
          </Access>
          <Access accessKey={"@deleteStore"}>
            <Popconfirm
              placement="top"
              title="确定要删除吗?"
              onConfirm={() => {
                handleRemove(record.id, actionRef);
              }}
              okText="确定"
              cancelText="取消"
            >
              <a onClick={() => {}}>删除</a>
            </Popconfirm>
            <Divider type="vertical" />
          </Access>

          <Access accessKey={"@storePriceManager"}>
            <a
              onClick={() => {
                handleStoreList(record);
                handleCommodityState(true);
              }}
            >
              售价管理
            </a>
          </Access>
          <Access accessKey={"@lklAddTerm"}>
            <Divider type="vertical" />
            <a
              onClick={() => {
                setLklTerm({
                  storeName:record.name,
                  user:record.contacts,
                  tel:record.tel,
                  address:record.address,
                  storeId:record.id
                });
                handleAddLklTerm(true);
              }}
            >
              增网增终
            </a>
          </Access>
        </>
      ),
    },
  ];
  const lklColumns = [
    {
      title: '店铺名',
      dataIndex: 'storeName',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '联系人',
      dataIndex: 'user',
      valueType: 'text',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '联系人为必填项',
          },
        ],
      },
    },
    {
      title: '联系人电话',
      dataIndex: 'tel',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '联系人电话为必填项',
          },
        ],
      },
    },
    {
      title: '地址',
      dataIndex: 'address',
      hideInTable: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '地址为必填项',
          },
        ],
      },
    },
    {
      title: '码表代码',

      dataIndex: 'storeArea',
      hideInTable: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '拉卡拉地区码表非0代码为必填项',
          },
        ],
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="店铺列表"
        actionRef={actionRef}
        formRef={formRef}
        rowKey="id"
        scroll={{ x: 1200 }}
        bordered
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Access accessKey={"@newStore"}>
            <Button
              type="primary"
              onClick={() => {
                setStoreLicense(null);
                handleModalVisible(true);
                setTreeValues(null);
                setPointData({});
                queryRule({});
                handleParentList();
              }}
            >
              <PlusOutlined /> 新建店铺
            </Button>
          </Access>
          ,
          <Access accessKey={"@importStore"}>
            <Upload
              name="file"
              action={() => {
                return `${defaultSetting.baseUrl}store/store/import`;
              }}
              listType="picture"
              showUploadList={false}
              maxCount={1}
              onChange={uploadOnChange}
              headers={{ token: sessionStorage.getItem('token'), type: 'ADMIN' }}
            >
              <Button type="primary" loading={uploadLoading} icon={<DownloadOutlined />}>
                导入店铺
              </Button>
            </Upload>
          </Access>
          ,
          <Access accessKey={"@exportStoreStock"}>
            <Button
              onClick={() => {
                handleOutModal(true);
              }}
              loading={uploadLoading}
              danger
              icon={<UploadOutlined />}
            >
              导出店铺库存
            </Button>
          </Access>
          ,
          <Access accessKey={"@exportStoreList"}>
            <Button
              onClick={() => {
                exportStore().then((res) => {
                  if (res) {
                    saveFileAs(res, '店铺');
                  }
                });
              }}
              loading={uploadLoading}
              danger
              icon={<UploadOutlined />}
            >
              导出店铺
            </Button>
          </Access>
          ,
          <a
            href={lklCodeUrl}
          >
            拉卡拉地区码表
          </a>
        ]}
        beforeSearchSubmit={(payload) => {
          return payload;
        }}
        request={(params, sorter, filter) => {
          return queryRule({ ...params });
        }}
        postData={(params) => {
          const { list, total } = params;
          transTitle(list);
          setCount(total);
          setMenuValues(list);
          return list || [];
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: true,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
        rowSelection={false}
        // options={false}
      />
      <CreateForm
        title="新增店铺"
        onCancel={() => {
          handleModalVisible(false);
          setMust(true);
        }}
        modalVisible={createModalVisible}
        width={800}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            if (value.parentId) {
              value.parentId.value ? (value.parentId = value.parentId.value) : null;
            }
            if (storeLicense){
              value.storeLicense = storeLicense;
            }
            const success = await handleAdd(value, actionRef);
            if (success) {
              handleModalVisible(false);
              setMust(true);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
          columns={columns}
        />
      </CreateForm>

      <CreateForm
        onCancel={() => handleCommodityState(false)}
        modalVisible={commodityState}
        width={1200}
      >
        <ProTable
          headerTitle={'【'+storeList.name + '】店铺价格明细'}
          actionRef={commodityRef}
          rowKey="id"
          scroll={{ x: 1200 }}
          bordered
          search={{
            labelWidth: 120,
          }}
          request={(params, sorter, filter) => {
            params.id = storeList.id;
            params.limit = params.pageSize;
            params.page = params.current;
            return storeCommodity(params);
          }}
          postData={(params) => {
            // transTitle(list);
            setCommodityCount(params.length);
            return params;
          }}
          pagination={{
            defaultPageSize: 10,
            showSizeChanger: true,
            showTitle: false,
            total: commodityCount,
            showTotal: (total) => `共${total}条`,
          }}
          columns={commodityColumns1}
          rowSelection={false}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
        />
      </CreateForm>
      <CreateForm
        title={commodityForms?.goodsItemName}
        modalVisible={priceState}
        onCancel={() => handlePriceState(false)}
        width={800}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            const { goodsId, goodsItemId, storeId, storeName } = commodityForms;
            value.goodsId = goodsId;
            value.goodsItemId = goodsItemId;
            value.storeId = storeId;
            value.storeName = storeName;
            value.cost ? null : (value.cost = 0);
            Object.assign(storeList, value);
            const success = await handleUpdatePrice(
              { id: goodsItemId, data: [value] },
              commodityRef,
            );
            if (success) {
              handlePriceState(false);
              if (commodityRef.current) {
                commodityRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={commodityColumns2}
          form={{
            initialValues: commodityForms,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
        />
      </CreateForm>
      <CreateForm
        title="修改店铺"
        onCancel={() => {
          setMust(true);
          handleEditModalVisible(false);
        }}
        modalVisible={createEditModalVisible}
        width={800}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            value.id = formValue.id;
            let newForm = JSON.parse(JSON.stringify(formValue));
            if (
              value.provinceId != newForm.provinceId &&
              (value.cityId == newForm.cityId || value.areaId == newForm.areaId)
            ) {
              message.warning('请正确选择所在市或所在区');
            } else {
              !areaSure ? (value.areaId = '') : null;
              if (value.parentId) {
                value.parentId.value ? (value.parentId = value.parentId.value) : null;
              }
              if (storeLicense){
                value.storeLicense = storeLicense;
              }
              const success = await handleUpdate(value, actionRef);
              if (success) {
                handleEditModalVisible(false);
                setMust(true);
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
          form={{
            initialValues: formValue,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
        />
      </CreateForm>
      {/* <CreateForm
        onCancel={() => handleStoreMasterModalVisible(false)}
        modalVisible={storeMasterModalVisible}
        width={1400}
        title={false}
      >
        <MasterList storeId={storeId} />
      </CreateForm> */}
      <CreateForm
        onCancel={() => handleStoreDashboardModalVisible(false)}
        modalVisible={storeDashboardModalVisible}
        width={1400}
        title={false}
      >
        <Dashboard storeId={storeId} />
      </CreateForm>
      <CreateForm
        onCancel={() => handleCodeModalVisible(false)}
        modalVisible={codeModalVisible}
        width={400}
        title={false}
      >
        <div style={{ padding: 10, fontSize: 22 }}>
          验证码：
          {
            <img
              src={codeUrl}
              alt=""
              style={{
                marginRight: 15,
              }}
            />
          }
        </div>
      </CreateForm>

      <CreateForm
        title={'导出信息'}
        width={800}
        footer={null}
        onCancel={() => handleOutModal(false)}
        modalVisible={outModal}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            exportStoreStock({
              storeIds: value.storeIds? value.storeIds.join(","):[]
            }).then((res) => {
              if (res) {
                saveFileAs(res, '店铺库存');
              }
            });
          }}
          rowKey="id"
          bordered
          type="form"
          columns={outColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
        />
      </CreateForm>
      <CreateForm
        title={'拉卡拉增网增终'}
        width={800}
        footer={null}
        onCancel={() => handleAddLklTerm(false)}
        modalVisible={addLklTerm}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            handSubmitButtonLoading(true);
            value.storeId = lklTerm.storeId;
            lklAddTerm(value).then(res=>{
              if (res && res.data){
                let code = res.data.code;
                Modal.confirm({
                  title: '增网增终成功!',
                  content: '激活码: '+code
                });
                handSubmitButtonLoading(false);
              }
            })
          }}
          rowKey="id"
          bordered
          type="form"
          columns={lklColumns}
          form={{
            initialValues: lklTerm,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
            submitter: {
              submitButtonProps: {
                loading: submitButtonLoading,
              },
            },
          }}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
